/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.jy.framework.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.jy.api.form.LoginForm;
import com.jy.api.form.RegisterForm;
import com.jy.api.utils.JwtUtils;
import com.jy.framework.exception.MyException;
import com.jy.framework.sys.entity.SysUserEntity;
import com.jy.framework.sys.service.SysUserService;
import com.jy.framework.sys.shiro.ShiroUtils;
import com.jy.framework.sys.shiro.UsernamePasswordUserTypeToken;
import com.jy.framework.utils.R;
import com.jy.framework.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
@Api(tags = "登录相关")
public class SysLoginController {
	@Autowired
	private Producer producer;
	@Autowired
	private JwtUtils jwtUtils;
	@Autowired
	private SysUserService service;
	/**
	 * 登录
	 */
	@PostMapping("/login/api")
	@ApiOperation("登录")
	@ResponseBody
	public R login(@RequestBody LoginForm form) {
		//表单校验
		ValidatorUtils.validateEntity(form);
		//用户登录
		SysUserEntity sysUserEntity = service.getOne(new QueryWrapper<SysUserEntity>().lambda().eq(SysUserEntity::getUsername, form.getMobile()));
		if (sysUserEntity == null){
			throw new MyException("用户名或密码错误！");
		}
		service.doLogin(sysUserEntity.getUsername(), form.getPassword(), sysUserEntity.getUserType());

		//生成token,传入 真实 password
		String token = jwtUtils.generateToken(sysUserEntity,form.getPassword());
		Map<String, Object> map = new HashMap<>(2);
		map.put("token", token);
		map.put("expire", jwtUtils.getExpire());

		return R.ok(map);
	}

	@ApiOperation("403:未登录或登陆超时")
	@RequestMapping(value = "/login/denide", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public R denide() {
		return R.error(403, "未登录或登陆超时");
	}
	///sys/anon/denide
	@PostMapping("/login/register")
	@ApiOperation("注册")
	@ResponseBody
	public R register(@RequestBody RegisterForm form) {
		//表单校验
		ValidatorUtils.validateEntity(form);

		SysUserEntity user = new SysUserEntity();
		user.setMobile(form.getMobile());
		user.setUsername(form.getMobile());
		user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
		user.setCreateTime(new Date());
		service.save(user);

		return R.ok();
	}
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response,HttpServletRequest request)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
//		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/login/sys", method = RequestMethod.POST)
	public R login(String username, String password,Integer userType, String captcha,HttpServletResponse response,HttpServletRequest request) {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//		String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//		 此处方便测试开发，不走验证码和登录，默认就是admin
		if(!captcha.equalsIgnoreCase(kaptcha)){
			throw new MyException("验证码不正确");
		}
//		username="admin";
//		password="juice";
		service.doLogin(username, password, userType);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("userType",userType);
		return R.ok(map);
	}


	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}

}
